<template>
	<view class="shopping-cart">
		<!-- 购物车为空时显示 -->
		<view v-if="cartList.length === 0" class="empty-cart">
			<image src="/static/images/empty-cart.png" mode="aspectFit"></image>
			<text>购物车还是空的</text>
			<button class="go-shopping" @tap="goShopping">去逛逛</button>
		</view>

		<!-- 购物车列表 -->
		<view v-else class="cart-content">
			<view class="cart-list">
				<view v-for="(item, index) in cartList" :key="index" class="cart-item">
					<van-swipe-cell>
						<van-card
							:num="item.productQuantity"
							:price="item.price"
							:title="item.productName"
							:thumb="item.productImagePath" 
							:desc="item.productDetails.length > 20 ? item.productDetails.substring(0,20) + '...' : item.productDetails"
							class="goods-card"
						>
							<template #footer>
								<van-button size="mini" @tap="updateQuantity(item, -1)">-</van-button>
								<van-button size="mini" @tap="updateQuantity(item, 1)">+</van-button>
								<van-button size="mini" type="danger" @tap="deleteItem(item)">删除</van-button>
							</template>
						</van-card>
						<template #right>
							<van-button square text="删除" type="danger" class="delete-button" @click="deleteItem(item)" />
						</template>
					</van-swipe-cell>
				</view>
			</view>

			<!-- 底部结算栏 -->
			<view class="cart-footer">
				<view class="total-price">
					<text>合计：</text>
					<text class="price">￥{{totalPrice}}</text>
				</view>
				<van-button type="danger" block @click="checkout">结算({{totalCount}}件)</van-button>
			</view>
		</view>
	</view>
</template>

<script>
import { getCartList, updateCartQuantity, deleteCartItem } from '@/api/shoppingCart.js'
import { getProductInfo } from '@/api/purchase.js'

export default {
	data() {
		return {
			cartList: [],
			totalPrice: 0,
			totalCount: 0
		}
	},
	onShow() {
		this.getCartList()
	},
	methods: {
		// 获取购物车列表
		async getCartList() {
			try {
				const res = await getCartList()
				console.log('购物车数据:', res)
				if (res.statusCode === 200 && res.data.code === 200) {
					// 获取每个商品的详细信息
					const cartItems = res.data.rows || []
					const detailedItems = await Promise.all(
						cartItems.map(async (item) => {
							try {
								const productRes = await getProductInfo(item.productId)
								if (productRes.statusCode === 200 && productRes.data.code === 200) {
									const productInfo = productRes.data.data
									return {
										...item,
										productName: productInfo.productName,
										productImagePath: productInfo.productImagePath,
										productDetails: productInfo.productDetails,
										price: productInfo.price
									}
								}
								return item
							} catch (error) {
								console.error('获取商品详情失败:', error)
								return item
							}
						})
					)
					
					this.cartList = detailedItems
					this.calculateTotal()
					console.log('购物车数据:', this.cartList)
				} else {
					uni.showToast({
						title: res.data.msg || '获取购物车列表失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('获取购物车列表失败:', error)
				uni.showToast({
					title: '获取购物车列表失败',
					icon: 'none'
				})
			}
		},
		
		// 更新商品数量
		async updateQuantity(item, change) {
			const newQuantity = item.productQuantity + change
			if (newQuantity < 1) return
			
			try {
				const res = await updateCartQuantity({
					cartId: item.cartId,
					productQuantity: newQuantity
				})
				console.log('更新数量:', res)
				if (res.data.code === 200) {
					// uni.showToast({
					// 	title: '更新成功',
					// 	icon: 'success'
					// })
					// 重新获取购物车列表
					await this.getCartList()
				}
			} catch (error) {
				console.error('更新数量失败:', error)
				uni.showToast({
					title: '更新数量失败',
					icon: 'none'
				})
			}
		},
		
		// 删除商品
		async deleteItem(item) {
			console.log('删除商品:', item.cartId)
			try {
				const res = await deleteCartItem(item.cartId)
				console.log('删除商品:', res)
				if (res.statusCode === 200 && res.data.code === 200) {
					uni.showModal({
						title: '提示',
						content: '确定要删除这个商品吗？',
						success: (res) => {
							if (res.confirm) {
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								})
							}
						}
					})
					this.getCartList()
				} else {
					uni.showToast({
						title: res.data.msg || '删除失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('删除商品失败:', error)
				uni.showToast({
					title: '删除失败',
					icon: 'none'
				})
			}
		},
		
		// 计算总价和总数量
		calculateTotal() {
			this.totalPrice = this.cartList.reduce((sum, item) => {
				return sum + (item.price * item.productQuantity)
			}, 0)
			this.totalCount = this.cartList.reduce((sum, item) => {
				return sum + item.productQuantity
			}, 0)
		},
		
		// 去结算
		checkout() {
			if (this.totalCount === 0) {
				uni.showToast({
					title: '请选择商品',
					icon: 'none'
				})
				return
			}
			// 跳转到结算页面
			uni.navigateTo({
				url: '/pages/checkout/checkout'
			})
		},
		
		// 去购物
		goShopping() {
			uni.switchTab({
				url: '/pages/index/index'
			})
		}
	}
}
</script>

<style lang="scss">
.shopping-cart {
	min-height: 100vh;
	background: #f5f7fa;
	padding-bottom: 120rpx;
}

.empty-cart {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 100rpx 0;
	
	image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 30rpx;
	}
	
	text {
		color: #909399;
		font-size: 28rpx;
		margin-bottom: 40rpx;
	}
	
	.go-shopping {
		width: 240rpx;
		height: 80rpx;
		line-height: 80rpx;
		background: #ff6b6b;
		color: #fff;
		border-radius: 40rpx;
		font-size: 28rpx;
	}
}

.cart-content {
	.cart-list {
		padding: 20rpx;
		
		.cart-item {
			margin-bottom: 20rpx;
			background: #fff;
			border-radius: 12rpx;
			overflow: hidden;
		}
	}
}

.cart-footer {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 100rpx;
	background: #fff;
	display: flex;
	align-items: center;
	padding: 0 30rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	
	.total-price {
		flex: 1;
		font-size: 28rpx;
		
		.price {
			color: #ff6b6b;
			font-size: 36rpx;
			font-weight: bold;
		}
	}
	
	.van-button {
		width: 240rpx;
	}
}

.goods-card {
	margin: 0;
	background-color: #ffffff;
}

.delete-button {
	height: 100%;
}
</style>